package com.fancy.application.sys.auth.filter;


import cn.hutool.core.util.StrUtil;
import com.fancy.application.common.filter.IFancyHandlerFilter;
import com.fancy.application.common.utils.SpringBeanUtil;
import com.fancy.application.common.utils.UserUtil;
import com.fancy.application.sys.org.entity.SysOrgPerson;
import com.fancy.application.sys.org.service.ISysOrgPersonService;
import com.fancy.application.sys.org.service.impl.SysOrgPersonServiceImpl;
import com.fancy.application.sys.permission.service.ISysPermissionMatcher;
import com.fancy.application.sys.permission.service.impl.SysPermissionMatcher;
import lombok.extern.log4j.Log4j2;
import org.apache.catalina.User;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.*;
import java.io.IOException;
import java.util.Arrays;

/**
 * 权限认证过滤器
 */

@Log4j2
public class FancyPermissionFilter extends AccessControlFilter {

    private final String[] noPermissionUrl = {"/sys/permission/sys_permission_url/checkPermission"};
    private ISysPermissionMatcher sysPermissionMatcher;

    public ISysPermissionMatcher getSysPermissionMatcher() {
        if(sysPermissionMatcher == null){
            sysPermissionMatcher = SpringBeanUtil.getBean(SysPermissionMatcher.class);
        }
        return sysPermissionMatcher;
    }


    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        String url = getPathWithinApplication(request);
        HttpServletRequest httpServletRequest = (HttpServletRequest)request;
        if(UserUtil.isAdmin()|| Arrays.stream(noPermissionUrl).anyMatch(u-> StrUtil.equals(u,url))){
            return true;
        }else{
            return getSysPermissionMatcher().doMatch(url,httpServletRequest.getMethod());
        }
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletResponse httpServletResponse = (HttpServletResponse)response;
        WebUtils.toHttp(response).sendError(httpServletResponse.SC_FORBIDDEN);
        return false;
    }
}
